/*
   Copyright 2022 cmanlh

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
*/
import JscNumber from './number.js';
import JscUtil from './util.js';
export default class JscForm extends HTMLElement {
    static get observedAttributes() { return ['jscreport', 'action', 'method'] }

    #observer;
    #bind = null;
    #proxyOfBind = null;
    #action = null;
    #method = "POST";

    constructor() {
        super();
        this.#init();
    }

    connectedCallback() {
        let self = this;
        self.#observer = new MutationObserver(function (mutationList, observer) {
            let stamp = Date.now();
            mutationList.forEach((mutation) => {
                switch (mutation.type) {
                    case 'childList': {
                        mutation.addedNodes.forEach((el) => {
                            if (el.nodeType == Node.ELEMENT_NODE) {
                                if (el.hasAttribute('jscbind')) {
                                    el.bind = self.#proxyOfBind;
                                    el.bindRefresh(stamp);
                                }
                            }
                        });
                        break;
                    }
                }
            });
        });
        self.#observer.observe(self, { childList: true });
    }

    disconnectedCallback() {
        if (null != this.#observer) {
            this.#observer.disconnect();
            this.#observer = null;
        }
    }

    set bind(data) {
        let self = this;
        self.#bind = data;
        self.#proxyOfBind = new Proxy(self.#bind, {
            set: function (obj, prop, value, receiver) {
                let propNodes = prop.split('.');
                switch (propNodes.length) {
                    case 1: {
                        obj[propNodes[0]] = value;
                        break;
                    }
                    default: {
                        let bindValue = obj[propNodes[0]];
                        if (null == bindValue || undefined == bindValue) {
                            if (Number.isIntegerStr(propNodes[1])) {
                                obj[propNodes[0]] = [];
                            } else {
                                obj[propNodes[0]] = {};
                            }
                            bindValue = obj[propNodes[0]];
                        }
                        let lastIdx = propNodes.length - 1;
                        for (let idx = 1; idx < lastIdx; idx++) {
                            let bindValueTmp = bindValue[propNodes[idx]];
                            if (null == bindValueTmp || undefined == bindValueTmp) {
                                if (Number.isIntegerStr(propNodes[idx + 1])) {
                                    bindValue[propNodes[idx]] = [];
                                } else {
                                    bindValue[propNodes[idx]] = {};
                                }
                            }
                            bindValue = bindValue[propNodes[idx]];
                        }
                        bindValue[propNodes[lastIdx]] = value;
                        break;
                    }
                }
                let bindRefreshStamp = Date.now();
                self.querySelectorAll('[jscbind="'.concat(prop).concat('"]')).forEach((el) => el.bindRefresh(bindRefreshStamp));
                return true;
            },
            get: function (obj, prop, receiver) {
                let propNodes = prop.split('.');
                let value = obj[propNodes[0]];
                if (null == value || undefined == value) {
                    return null;
                }
                for (let idx = 1; idx < propNodes.length; idx++) {
                    value = value[propNodes[idx]];
                    if (null == value || undefined == value) {
                        return null;
                    }
                }
                return value;
            }
        });
        self.querySelectorAll('[jscbind]').forEach((el) => el.bind = self.#proxyOfBind);
        let bindRefreshStamp = Date.now();
        self.bindRefresh(bindRefreshStamp);
    }

    get bind() {
        return this.#bind;
    }

    fetchProxyOfBind() {
        return this.#proxyOfBind;
    }

    bindRefresh() {
        let bindRefreshStamp = Date.now();
        this.querySelectorAll('[jscbind]').forEach((el) => el.bindRefresh(bindRefreshStamp));
    }

    async doAction() {
        let self = this;
        if (self.#action) {
            if ('GET' == self.#method) {
                return JscUtil.get(self.#action, this.#bind);
            } else {
                return JscUtil.post(self.#action, this.#bind);
            }
        }
    }

    #init() {
        let self = this;
        self.#action = self.getAttribute('action');
        let methodValue = self.getAttribute('method');
        if (methodValue) {
            self.#method = methodValue;
        }
    }
}

if (!customElements.get('jsc-form')) {
    window.customElements.define("jsc-form", JscForm);
}